<?php

namespace Encore\Admin\Controllers;

use Cache;
use Encore\Admin\Auth\Database\Menu;
use Encore\Admin\Layout\Content;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;

/**
 * @property string input
 */
class AdminController extends Controller
{
    use HasResourceActions;

    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'Title';

    /**
     * Set description for following 4 action pages.
     *
     * @var array
     */
    protected $description = [];

    /**
     * Get content title.
     *
     * @return string
     */
    protected function title()
    {
        return $this->title;
    }

    public function __construct()
    {
        $uriTitles = Cache::remember(Menu::$cacheKey, now()->addDay(), function () {
            return Menu::query()->whereNotNull('uri')->pluck('title', 'uri')->toArray();
        });
        //clear number from path
        $path = preg_replace('/[0-9]+/', '', request()->path());
        $path = Str::replaceLast('/edit', '', $path);
        $path = Str::replace(['create'], ['', ''], $path);
        $paths = array_filter(explode('/', $path));
        $path = end($paths);
        $this->title = data_get($uriTitles, $path, $this->title);
    }


    /**
     * Index interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['index'] ?? trans('admin.list'))
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     *
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['show'] ?? trans('admin.show'))
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     *
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['create'] ?? trans('admin.create'))
            ->body($this->form());
    }
}
